{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f04dd603-a2d1-48ce-8c17-9f1dba8de1ee",
   "metadata": {},
   "source": [
    "Chapter 07\n",
    "\n",
    "# 鸡兔同笼-用SymPy求解\n",
    "《线性代数》 | 鸢尾花书：数学不难"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ccafb456-2453-4c82-8a65-b1963a370cb2",
   "metadata": {},
   "source": [
    "该代码利用 **符号计算（Symbolic Computation）** 方法求解“鸡兔同笼”问题，这是一个 **线性方程组求解问题**，其中 **未知数 $x_1$ 和 $x_2$** 代表鸡和兔的数量。不同于数值计算，这里的 **符号计算** 允许我们得到**精确解析解**，避免浮点数误差。\n",
    "\n",
    "---\n",
    "\n",
    "## **数学建模**\n",
    "设鸡的数量为 $x_1$，兔的数量为 $x_2$，问题可以转换为如下的线性方程组：\n",
    "\n",
    "$$\n",
    "\\begin{cases}\n",
    "x_1 + x_2 = 35 \\quad &\\text{(总数量方程)} \\\\\n",
    "2x_1 + 4x_2 = 94 \\quad &\\text{(总腿数方程)}\n",
    "\\end{cases}\n",
    "$$\n",
    "\n",
    "将其写成矩阵形式：\n",
    "\n",
    "$$\n",
    "A \\mathbf{x} = \\mathbf{b}\n",
    "$$\n",
    "\n",
    "其中：\n",
    "$$\n",
    "A = \\begin{bmatrix} 1 & 1 \\\\ 2 & 4 \\end{bmatrix}, \\quad\n",
    "\\mathbf{x} = \\begin{bmatrix} x_1 \\\\ x_2 \\end{bmatrix}, \\quad\n",
    "\\mathbf{b} = \\begin{bmatrix} 35 \\\\ 94 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "目标是求解向量 $\\mathbf{x}$，即：\n",
    "\n",
    "$$\n",
    "\\mathbf{x} = A^{-1} \\mathbf{b}\n",
    "$$\n",
    "\n",
    "---\n",
    "\n",
    "## **代码解析**\n",
    "### **1. 定义系数矩阵 $A$ 和常数向量 $b$**\n",
    "代码使用 `sympy.Matrix` 定义 **符号矩阵** $A$ 和向量 $b$，不同于 `numpy` 的浮点运算，`sympy` 采用**符号表达式**存储数据，允许精确求解。\n",
    "\n",
    "$$\n",
    "A = \\begin{bmatrix} 1 & 1 \\\\ 2 & 4 \\end{bmatrix}, \\quad\n",
    "b = \\begin{bmatrix} 35 \\\\ 94 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "---\n",
    "\n",
    "### **2. 使用 LU 分解求解**\n",
    "代码调用 `A.LUsolve(b)`，它基于 **LU 分解（LU Decomposition）** 方法来解线性方程组。LU 分解的步骤如下：\n",
    "\n",
    "#### **(1) 分解矩阵 $A$**\n",
    "矩阵 $A$ 可以被分解为 **下三角矩阵** $L$ 和 **上三角矩阵** $U$，即：\n",
    "$$\n",
    "A = LU\n",
    "$$\n",
    "\n",
    "其中：\n",
    "$$\n",
    "L = \\begin{bmatrix} 1 & 0 \\\\ 2 & 1 \\end{bmatrix}, \\quad\n",
    "U = \\begin{bmatrix} 1 & 1 \\\\ 0 & 2 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "#### **(2) 先解 $L \\mathbf{y} = b$**\n",
    "引入中间变量 $\\mathbf{y}$，我们先解：\n",
    "\n",
    "$$\n",
    "\\begin{bmatrix} 1 & 0 \\\\ 2 & 1 \\end{bmatrix}\n",
    "\\begin{bmatrix} y_1 \\\\ y_2 \\end{bmatrix}\n",
    "=\n",
    "\\begin{bmatrix} 35 \\\\ 94 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "通过前代回代（Forward Substitution）得到：\n",
    "\n",
    "$$\n",
    "y_1 = 35, \\quad y_2 = 94 - 2 \\times 35 = 24\n",
    "$$\n",
    "\n",
    "#### **(3) 再解 $U \\mathbf{x} = \\mathbf{y}$**\n",
    "$$\n",
    "\\begin{bmatrix} 1 & 1 \\\\ 0 & 2 \\end{bmatrix}\n",
    "\\begin{bmatrix} x_1 \\\\ x_2 \\end{bmatrix}\n",
    "=\n",
    "\\begin{bmatrix} 35 \\\\ 24 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "通过后代回代（Backward Substitution）得到：\n",
    "\n",
    "$$\n",
    "x_2 = \\frac{24}{2} = 12\n",
    "$$\n",
    "$$\n",
    "x_1 = 35 - x_2 = 23\n",
    "$$\n",
    "\n",
    "最终求得：\n",
    "$$\n",
    "x_1 = 23, \\quad x_2 = 12\n",
    "$$\n",
    "\n",
    "---\n",
    "\n",
    "## **结论**\n",
    "该代码使用 `sympy` 进行符号计算，避免了浮点误差，并利用 **LU 分解** 逐步求解线性方程组。最终，我们得到了**解析解**：\n",
    "\n",
    "$$\n",
    "x_1 = 23, \\quad x_2 = 12\n",
    "$$\n",
    "\n",
    "这表明在鸡兔同笼问题中，共有 **23 只鸡，12 只兔子**。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d427f21-15b6-4155-9eea-ba333621cfaf",
   "metadata": {},
   "source": [
    "## 初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d530bc5e-a5b5-41cf-92e4-461541be8fc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sympy import Matrix"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dcea75fb-c19a-4f90-a0e9-b8556344174b",
   "metadata": {},
   "source": [
    "## 鸡兔同笼系数矩阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f1044cb0-92c2-4e07-8b42-b5571dfc9101",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\left[\\begin{matrix}1 & 1\\\\2 & 4\\end{matrix}\\right]$"
      ],
      "text/plain": [
       "Matrix([\n",
       "[1, 1],\n",
       "[2, 4]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = Matrix([[1, 1], \n",
    "            [2, 4]])\n",
    "A"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d759117-5643-4b86-a795-1ebf15aa254b",
   "metadata": {},
   "source": [
    "## 常数列向量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "954b7525-dcef-47cb-af13-40c741ca3891",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\left[\\begin{matrix}35\\\\94\\end{matrix}\\right]$"
      ],
      "text/plain": [
       "Matrix([\n",
       "[35],\n",
       "[94]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = Matrix([[35],\n",
    "            [94]])\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7799aec4-4734-49f7-b0c4-2d34344aa7be",
   "metadata": {},
   "source": [
    "## 使用符号计算求解 Ax = b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "aa3dd5d6-6437-4775-9611-64e4fbb5ef65",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\left[\\begin{matrix}23\\\\12\\end{matrix}\\right]$"
      ],
      "text/plain": [
       "Matrix([\n",
       "[23],\n",
       "[12]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用符号计算求解 Ax = b\n",
    "x = A.LUsolve(b)\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03232b1c-9ff6-41a6-8eb9-b5f98c289f77",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "070c3389-8048-43a3-baa7-6666009bce96",
   "metadata": {},
   "source": [
    "作者\t**生姜DrGinger**  \n",
    "脚本\t**生姜DrGinger**  \n",
    "视频\t**崔崔CuiCui**  \n",
    "开源资源\t[**GitHub**](https://github.com/Visualize-ML)  \n",
    "平台\t[**油管**](https://www.youtube.com/@DrGinger_Jiang)\t\t\n",
    "\t\t[**iris小课堂**](https://space.bilibili.com/3546865719052873)\t\t\n",
    "\t\t[**生姜DrGinger**](https://space.bilibili.com/513194466)  "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:base] *",
   "language": "python",
   "name": "conda-base-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
